package com.idcheck.rechcustoms;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import com.idcheck.rechcustoms.R;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.Toolbar;

import android.os.CountDownTimer;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

//import com.yanzhenjie.permission.AndPermission;
//import com.yanzhenjie.permission.PermissionListener;
//import com.yanzhenjie.permission.Rationale;
//import com.yanzhenjie.permission.RationaleListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import aar.test.tessocr.adapter.CabDetailAdapter;
import aar.test.tessocr.adapter.CompanySearchInfoAdapter;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CabDetailModel;
import aar.test.tessocr.model.CabinetModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.tessOcrUtil.MyGridView;
import aar.test.tessocr.utils.ConstantPara;
//import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.statuesBar;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import utils.OtherUtil;
import utils.PrefUtils;


public class ChioceCabActivity extends AppCompatActivity {

    public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");
    private RadioGroup gridRadioGroup;

    private Button open_grid;

    private TextView choiceCab_spinner;
    private TextView choiceCab_spinner2;
    private CountDownTimer mTimer=null; //UI计时
    private volatile long resetTimeStamp = 0;
    private volatile long brightTimeStamp = 0;
    private volatile long mCountSetting = 0;
    private volatile long countTimeStamp = 0;

    private List<CabinetModel> cabList;

    private List<String> data_list = new ArrayList<>();

    private int selectId = 0;

    private int cabType = 1;
    private int freeCount = 0;
    private ArrayAdapter<String> cabAdater;

    private Context mContext;

    private DisplayMetrics dm;

    private boolean isPerss=false;

    private  Toolbar toolbar;
    LinearLayout tv_back;
    private MyGridView cab_grid_view;

    private LinearLayout left_layout;

    private Button cab_open_all;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chioce_cab);
        mContext=this;
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initTimer();
        //mVisible = true;
        if(getSupportActionBar()!=null){

            getSupportActionBar().hide();

        }
        hideBottomUIMenu();
//        toolbar = (Toolbar) findViewById(R.id.toolbar_normal);
//        setSupportActionBar(toolbar);
        initView();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);



        tv_back = (LinearLayout) findViewById(R.id.ll_back);
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });






        companyCabDetail();
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (9999999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!ChioceCabActivity.this.isFinishing()) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 \n HH:mm:ss");// HH:mm:ss
//获取当前时间
                        Date date = new Date(System.currentTimeMillis());
                        TextView datetext = (TextView)findViewById(R.id.textDate);
                        datetext.setText(simpleDateFormat.format(date));
                        TextView weektext = (TextView)findViewById(R.id.textWeek);
                        weektext.setText(getWeek());
                        if(resetTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - resetTimeStamp;
                            if(timeOut > 180000){
                                resetView();
                            }
                        }


                        if(countTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - countTimeStamp;
                            if(timeOut > 3000){
                                mCountSetting = 0;
                                countTimeStamp = 0;
                            }
                        }

                        int hours = date.getHours();
                        int minutes = date.getMinutes();
                        int seconds = date.getSeconds();


                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public static String getWeek(){
        Calendar cal = Calendar.getInstance();
        int i = cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message) {
        switch (message.what) {
            case 1600:
                EventMessageForSaveAuth(message.obj);
                break;
            case 1700:
                EventMessageForSaveOpen(message.obj);
                break;
            case 1200:
                restartApplication();
                break;
            default:
                EventMessageForError(message.what);
                break;

        }
    }
    private void resetView(){
        finish();
    }
    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        EventBus.getDefault().unregister(this);
        unInitTimer();
    }
    private void initView(){


        cab_open_all=findViewById(R.id.cab_open_all);
        cab_open_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = PrefUtils.getString(ChioceCabActivity.this, "phone", "0");
                new FetchSaveOpenTask(phone).execute();

            }
        });



        cab_grid_view=findViewById(R.id.cab_grid_view);

        cab_grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if(null!=mList&&mList.size()>0){

                    BaseApplication.getIntance().setmCabDetailModel(mList.get(position));
                    startActivity(new Intent(ChioceCabActivity.this, CabInfoActivity.class));
                }




            }
        });

//        left_layout=findViewById(R.id.left_layout);
//        left_layout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

    }

    private List<CabDetailModel> mList;
    private void companyCabDetail(){


        Map<String ,Object> map=new HashMap<>();
        int adminId = Integer.parseInt(PrefUtils.getString(ChioceCabActivity.this, "adminid", "0"));
        int cabinetId = Integer.parseInt(PrefUtils.getString(ChioceCabActivity.this, "cabinetid", "0"));

        map.put("cabinetId",cabinetId);
        map.put("adminid",adminId);

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse<List<CabDetailModel>>>post(NetworkLogic.URL_CABINETDETAIL)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<CabDetailModel>>>(ChioceCabActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<CabDetailModel>>> response) {


                        Log.e("MainActivity","onSuccess-----logout---------------");

                        if(null!=response.body().data&&response.body().data.size()>0){
                            mList=new ArrayList<>();
                            mList=response.body().data;
                            for(CabDetailModel  item:mList){
                                Log.d("Item", item.toString());
                                if(null!=item.getIsUse()&&1==Integer.valueOf(item.getIsUse()))
                                {
                                    freeCount++;
                                }
                            }

                            String formattedString = String.format("内部使用(%d)", freeCount);

                            cab_open_all.setText(formattedString);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    cab_grid_view.setVisibility(View.VISIBLE);
                                    CabDetailAdapter adapter = new CabDetailAdapter(mContext,mList);
                                    cab_grid_view.setAdapter(adapter);


                                }
                            });
                        }else{


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    cab_grid_view.setVisibility(View.GONE);
                                }
                            });



                        }





                    }

                    @Override
                    public void onError(Response<LzyResponse<List<CabDetailModel>>> response) {
                        Log.e("MainActivity","onError---------------------");
                    }
                });



    }




    private void openAllCab(){

//        if(null==BaseApplication.getIntance().getLoginBean()){
//            return;
//        }
//
//        if(null==BaseApplication.getIntance().getLoginBean().getCabinetId()){
//            return;
//        }

        Map<String ,Object> map=new HashMap<>();
        int adminId = Integer.parseInt(PrefUtils.getString(ChioceCabActivity.this, "adminid", "0"));
        int cabinetId = Integer.parseInt(PrefUtils.getString(ChioceCabActivity.this, "cabinetid", "0"));

        map.put("cabinetId",cabinetId);
        map.put("type",1);

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse>post(NetworkLogic.URL_ADMINOPENGRID)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse>(ChioceCabActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse> response) {


                        Log.e("MainActivity","onSuccess-----logout---------------"+response.body().data);


                        if(null!=response.body().msg){
                            Toast.makeText(mContext,response.body().msg,Toast.LENGTH_LONG).show();
                        }


                    }

                    @Override
                    public void onError(Response<LzyResponse> response) {
                        Log.e("MainActivity","onError---------------------");
                        if(null!=response.body().msg){
                            Toast.makeText(mContext,response.body().msg,Toast.LENGTH_LONG).show();}
                    }
                });



    }







    private void resetViewMessage(){

    }
    private void EventMessageForSaveOpen(Object obj){
        try{

            //findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            //findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

//                ImageView resultimg = findViewById(R.id.resultimg);
//                resultimg.setImageResource(R.drawable.right);
//                TextView resulttext = findViewById(R.id.resulttext);
//                resulttext.setText(result.getString("msg"));
                Toast.makeText(ChioceCabActivity.this,result.getString("msg"),Toast.LENGTH_LONG).show();
//                final Timer t = new Timer();
//                t.schedule(new TimerTask() {
//                    public void run() {
//                        t.cancel();
//                        resetViewMessage();
//                    }
//                }, 5000);
            }else{
                Toast.makeText(ChioceCabActivity.this,result.getString("msg"),Toast.LENGTH_LONG).show();
//                ImageView resultimg = findViewById(R.id.resultimg);
//                resultimg.setImageResource(R.drawable.error);
//                TextView resulttext = findViewById(R.id.resulttext);
//                resulttext.setText(result.getString("msg"));
//                final Timer t = new Timer();
//                t.schedule(new TimerTask() {
//                    public void run() {
//                        t.cancel();
//                        resetViewMessage();
//                    }
//                }, 5000);
            }

        }catch(Exception e){
//            ImageView resultimg = findViewById(R.id.resultimg);
//            resultimg.setImageResource(R.drawable.warning);
//            TextView resulttext = findViewById(R.id.resulttext);
//            resulttext.setText("请检查网络");
            Toast.makeText(ChioceCabActivity.this,"请检查网络",Toast.LENGTH_LONG).show();
//            final Timer t = new Timer();
//            t.schedule(new TimerTask() {
//                public void run() {
//                    t.cancel();
//                    resetViewMessage();
//                }
//            }, 5000);
        }
    }
    private void EventMessageForSaveAuth(Object obj){
        try{


            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                PrefUtils.setString(this, "adminid", result.getJSONObject("data").getString("id"));
                PrefUtils.setString(this, "cabinetid", result.getJSONObject("data").getString("cabinetid"));

//                companyMobile = findViewById(R.id.savePhone);
//                password.setText("");
//                findViewById(R.id.step11).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                findViewById(R.id.step12).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
//
//                int count = result.getJSONObject("data").getInt("count");
//                if(count != 0){
//                    TextView saveresult = findViewById(R.id.saveresult);
//                    String text = "有"+String.valueOf(count)+"空位";
//                    saveresult.setText(text);
//                    saveresult.setTextColor(Color.BLACK);
//                    findViewById(R.id.savesubmit).setEnabled(true);
//                    findViewById(R.id.ordersubmit).setEnabled(true);
//                }else{
//                    TextView saveresult = findViewById(R.id.saveresult);
//                    String text = "暂无空位";
//                    saveresult.setText(text);
//                    saveresult.setTextColor(Color.RED);
//                    findViewById(R.id.savesubmit).setEnabled(false);
//                    findViewById(R.id.ordersubmit).setEnabled(false);
//                }
                resetTimeStamp = System.currentTimeMillis();
            }else{
//                findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
//                ImageView resultimg = findViewById(R.id.resultimg);
//                resultimg.setImageResource(R.drawable.warning);
//                TextView resulttext = findViewById(R.id.resulttext);
//                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            e.printStackTrace();
            resetView();
        }
    }
    private void EventMessageForError(int what){
        switch(what){
            case 1101:
                Toast.makeText(ChioceCabActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                break;
            case 1301:
//                if(OtherUtil.isKeyboardActive(getWindow())){
//                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
//                }
                //resetView();
                break;
            case 1401:
                if(OtherUtil.isKeyboardActive(getWindow())){
                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
                }
                //resetView();
                break;
            case 1501:
                Toast.makeText(ChioceCabActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;
            case 1701:
                Toast.makeText(ChioceCabActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;

        }
    }

}
